package com.nuanshui.heatedloan.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

import org.apache.commons.lang3.Validate;

public class Digests {

	public Digests() {
	}

	public static byte[] sha1(final byte input[]) {
		return digest(input, "SHA-1", null, 1);
	}

	public static byte[] sha1(final byte input[], final byte salt[]) {
		return digest(input, "SHA-1", salt, 1);
	}

	public static byte[] sha1(final byte input[], final byte salt[],
			final int iterations) {
		return digest(input, "SHA-1", salt, iterations);
	}

	private static byte[] digest(final byte input[], final String algorithm,
			final byte salt[], final int iterations) {
		try {
			final MessageDigest digest = MessageDigest.getInstance(algorithm);
			if (salt != null)
				digest.update(salt);
			byte result[] = digest.digest(input);
			for (int i = 1; i < iterations; i++) {
				digest.reset();
				result = digest.digest(result);
			}

			return result;
		} catch (final GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	public static byte[] generateSalt(final int numBytes) {
		Validate.isTrue(numBytes > 0,
				"numBytes argument must be a positive integer (1 or larger)",
				numBytes);
		final byte bytes[] = new byte[numBytes];
		random.nextBytes(bytes);
		return bytes;
	}

	public static byte[] md5(final InputStream input) throws IOException {
		return digest(input, "MD5");
	}

	public static byte[] sha1(final InputStream input) throws IOException {
		return digest(input, "SHA-1");
	}

	private static byte[] digest(final InputStream input, final String algorithm)
			throws IOException {
		try {
			final MessageDigest messageDigest = MessageDigest
					.getInstance(algorithm);
			final int bufferLength = 8192;
			final byte buffer[] = new byte[8192];
			for (int read = input.read(buffer, 0, 8192); read > -1; read = input
					.read(buffer, 0, 8192))
				messageDigest.update(buffer, 0, read);

			return messageDigest.digest();
		} catch (final GeneralSecurityException e) {
			throw Exceptions.unchecked(e);
		}
	}

	private static final String SHA1 = "SHA-1";
	private static final String MD5 = "MD5";
	private static SecureRandom random = new SecureRandom();

}
